//
//  YDOAInventoryManageVC.swift
//  
//
//  Created by 占益民 on 2017/11/22.
//

import UIKit
import HandyJSON
import Toaster

let STOCKREUSEID = "YDOAStockCell"

class YDOAInventoryManageVC: UIViewController {

    @IBOutlet weak var myTableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!
    
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
    
    lazy var dataSource : NSMutableArray = NSMutableArray()
    var page : Int? = 1
    var type : Bool! = false // false 下拉刷新   true 上拉加载
    var isSearch : Bool! = false //false 不是搜索  true   是搜索
    
    
    override func viewWillAppear(_ animated: Bool) {
        loadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "库存管理"
        self.navigationController?.navigationBar.isHidden = false
        self.automaticallyAdjustsScrollViewInsets = false
        self.edgesForExtendedLayout = .init(rawValue: 0)
        
        // 设置导航栏右上角的按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "添加库存", style: .plain, target: self, action: #selector(addStock))
        
        //设置searchbar 的样式
        self.searchBar.showsCancelButton = true //显示取消按钮
        
     
        myTableView.register(UINib(nibName: "YDOAStockCell", bundle: nil), forCellReuseIdentifier: STOCKREUSEID)
        weak var weakSelf = self
        myTableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            weakSelf?.page = 1
            weakSelf?.type = false
            weakSelf?.loadData()
        })
        myTableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            weakSelf?.page = (weakSelf?.page!)! + 1
             weakSelf?.type = true
            weakSelf?.loadData()
        })
        //加载数据
        loadData()

        // Do any additional setup after loading the view.
    }

    //添加库存
    @objc func addStock(){
         navigationController?.pushViewController(YDOAAddStockVC(), animated: true)
    }
    
    func loadData(){
        var urlStr : String! = ""
        if !self.isSearch {
             urlStr = String(format:GET_STOCK_LIST,self.page!)
        }else{
            urlStr = String(format:SEARCH_STOCK_LIST,searchBar.text!)
            YMLog.log(item: urlStr)
        }
        
        YMLog.log(item: urlStr)
        YMNetworkManager().getRequest(urlString: urlStr, params: nil, success: { (responser) in
            YMLog.log(item: responser)
            if responser["status"]?.int8Value == 1{
                let dataArr = responser["data"] as! NSArray
                if !self.type {
                    self.dataSource.removeAllObjects()
                }
                for dict in dataArr {
                    guard let model = JSONDeserializer<YDOAStockModel>.deserializeFrom(dict: dict as? NSDictionary) else{ return }
                    self.dataSource.add(model)
                }
                self.myTableView.mj_header.endRefreshing()
                self.myTableView.mj_footer.endRefreshing()
                self.myTableView.reloadData()
            }else{
                Toast(text: (responser["message"] as! String), delay: 0, duration: 1.5).show()
            }
        }) { (error) in
            
        }
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


//MARK :  --  tableView  代理方法
extension YDOAInventoryManageVC : UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return  self.dataSource.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 132
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: STOCKREUSEID) as? YDOAStockCell else { return YDOAStockCell() }
        cell.selectionStyle = .none
        cell.index = indexPath.row
        let model =  self.dataSource[indexPath.row] as? YDOAStockModel
        cell.type = 2 //库存界面进入
        cell.model = model
    
        weak var weakSelf =  self
        cell.callback = {(index : Int, type : Int) in
            //type 1 删除   2  修改
            if type == 1{
              guard let model  = weakSelf?.dataSource[indexPath.row] as? YDOAStockModel else{return}
//                let params = ["pid":model.id]
                let urlStr = String(format:DELETE_STOCK,(model.id)!)
                YMNetworkManager().getRequest(urlString:urlStr , params: nil, success: { (responser) in
                    if responser["status"]?.int8Value == 1{
                        Toast(text: responser["message"] as? String, delay: 0, duration: 1.5).show()
                       weakSelf?.loadData()
                    }else{
                        Toast(text: responser["message"] as? String, delay: 0, duration: 1.5).show()
                    }
                }, failture: { (error) in
                    
                })
                
                
            }else{
                guard let model  = weakSelf?.dataSource[indexPath.row] as? YDOAStockModel else{return}
                let vc = YDOAEditStockVC()
                vc.model = model
            weakSelf?.navigationController?.pushViewController(vc, animated: true)
            }
        }
        
        return cell
    }
  
    
}


extension YDOAInventoryManageVC : UISearchBarDelegate {
    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
//        searchBar.showsCancelButton = true //显示取消按钮
        return true
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        YMLog.log(item: "取消搜索")
        searchBar.text = ""
        view.endEditing(true)
        page = 1
        isSearch = false
        self.type = true
        loadData()
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
//        searchBar.showsCancelButton = false //隐藏取消按钮
        view.endEditing(true)
        isSearch = true
        self.type = false
        loadData()
//        YMLog.log(item: "开始搜索")
    }
    

}



